package servlet;

import dao.RegisterDao;
import text.UserBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");

        //定义session对象
        HttpSession session = req.getSession();
        //获取存储在session对象中的验证码对象
        String checkCodeImg = (String) session.getAttribute("checkCode");

        if (checkCodeImg != null && checkCodeImg.equalsIgnoreCase(checkCode)) {
            //保证验证码的一次性
            session.removeAttribute("checkCodeImg");
            //如果验证码相同，就注册用户
            UserBean user = new UserBean();
            user.setUsername(username);
            user.setPassword(password);

            //判断是否注册成功，如果成功，重定向跳转登录界面，失败，给出提示
            if (new RegisterDao().registerDao(user)) {
                resp.sendRedirect(req.getContextPath() + "/index.jsp");
            } else {
                //用户名重复，将错误储存在request中，转发到register.jsp
                req.setAttribute("userDuplication", "用户名重复");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
            }
        } else {
            //如果验证码不对，则将错误存储在request中，转发到register.jsp
            req.setAttribute("checkCodeError", "验证码错误！");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
    }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
